﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Data;
using System.Collections;
using System.Web;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web.UI;

//using System.Web.Script.Serialization;
namespace weikebuluo.DBUtility
{

	//2013-11-26 16:16:43 谢俊

	public class CommonFn
	{

		public static string GetNow()
		{
			return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
		}

		//easyui表格加载数据出错提示
		public static void LoadListErrorInfo(Exception e, ref string result)
		{
			result = "{\"total\":1" + ",\"rows\":[{\"error\":\"" + e.Message + "\"}]}";
		}




		#region 数据库操作


		#region basic

		//FormToHashtable

		public static Hashtable FormToHashtable()
		{
			string[] allKeys = HttpContext.Current.Request.Form.AllKeys;
			Hashtable h = new Hashtable();
			for (int i = 0; i < allKeys.Length; i++)
			{
				string[] values = HttpContext.Current.Request.Form.GetValues(i);
				for (int j = 0; j < values.Length; j++)
				{
					//不允许出现key重复的情况
					AddKey(ref h, allKeys[i], values[j]);
					//h.Add(allKeys[i], values[j]);
				}
			}
			return h;
		}

		//添加键值
		public static void AddKey(ref Hashtable h, string key, string value)
		{
			if (h[key] == null)
			{
				h.Add(key, value);
			}
			else
			{
				h[key] = value;
			}
		}
		#endregion

		#region CRUD-2013-11-14 14:13:54

		#region sql操作

		public static int Add(DataTable dt, string tableName, Hashtable values) {

			return int.Parse(DbHelperSQL.GetSingle(CreateInsert(tableName,dt,values)).ToString());
		}

		public static int Add(string tableName, Hashtable values)
		{
			return int.Parse(DbHelperSQL.GetSingle(CreateInsert(tableName, values)).ToString());
		}

		public static int Update(DataTable dt, string tableName, string sqlWhere, Hashtable values)
		{
			return int.Parse(DbHelperSQL.ExecuteSql(CreateUpdate(tableName,dt,sqlWhere,values)).ToString());
		}

		public static int Update(string tableName, string sqlWhere, Hashtable values)
		{

			return int.Parse(DbHelperSQL.ExecuteSql(CreateUpdate(tableName, sqlWhere, values)).ToString());
		}

		public static bool Delete(string tableName, string sqlWhere)
		{
			return (DbHelperSQL.ExecuteSql(CreateDel(tableName, sqlWhere)) > 0);
		}

		public static DataSet GetList(string tableName, string sqlWhere, string fieldNames = "*")
		{
			return DbHelperSQL.Query(CreateSelect(tableName, sqlWhere, fieldNames));
		}
		#endregion

		#region 创建sql语句

		/// <summary>
		/// 
		/// </summary>
		/// <param name="modelJsonData">json数据</param>
		/// <returns></returns>
		public static DataTable GetTableInfo(string modelJsonData)
		{
			DataTable dt = GetBasicTableInfo();

			string str = modelJsonData.Replace("{", "").Replace("}", "").Replace("\"", "");

			string[] comma = str.Split(',');
			string[] colon = null;
			for (int i = 0; i < comma.Length; i++)
			{
				colon = comma[i].Split(':');
				DataRow dr = dt.NewRow();
				dr["fieldName"] = colon[0].Trim();
				if (colon[0].Trim() == "Identity")
				{
					dr["fieldName"] = colon[1].Trim();
					dr["idField"] = colon[1].Trim();
				}
				dt.Rows.Add(dr);
			}
			return dt;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="model">实体</param>
		/// <returns></returns>
		public static DataTable GetTableInfo(object model)
		{
			DataTable dt = GetBasicTableInfo();
			PropertyInfo[] pi = model.GetType().GetProperties();
			string idField = "";
			foreach (PropertyInfo p in pi)
			{
				if (p.Name.Trim() == "TableName")
				{
					continue;
				}
				DataRow dr = dt.NewRow();
				//p.PropertyType.Name
				dr["fieldName"] = p.Name.Trim();
				dr["typeName"] = p.PropertyType.Name;

				if (p.Name.Trim() == "Identity")
				{
					idField = p.GetValue(model, null).ToString();
					continue;
				}

				dr["typeName"] = dr["typeName"].ToString().Trim().Equals("Nullable`1") ? "Int32" : dr["typeName"];


				dr["typeName"] = ChangeToSqlType(dr["typeName"].ToString());
				dt.Rows.Add(dr);
			}
			foreach (DataRow r in dt.Rows)
			{
				if (r["fieldName"].ToString().Trim().Equals(idField)) {
					r["idField"] = idField;
				}
			}
			return dt;
		}


		/// <summary>
		/// 数据库中与C#中的数据类型对照
		/// </summary>
		/// <param name="type"></param>
		/// <returns></returns>
		private string ChangeToCSharpType(string type)
		{
			string reval = string.Empty;
			switch (type.ToLower())
			{
				case "int":
				reval = "Int32";
				break;
				case "text":
				reval = "String";
				break;
				case "bigint":
				reval = "Int64";
				break;
				case "binary":
				reval = "System.Byte[]";
				break;
				case "bit":
				reval = "Boolean";
				break;
				case "char":
				reval = "String";
				break;
				case "datetime":
				reval = "System.DateTime";
				break;
				case "decimal":
				reval = "System.Decimal";
				break;
				case "float":
				reval = "System.Double";
				break;
				case "image":
				reval = "System.Byte[]";
				break;
				case "money":
				reval = "System.Decimal";
				break;
				case "nchar":
				reval = "String";
				break;
				case "ntext":
				reval = "String";
				break;
				case "numeric":
				reval = "System.Decimal";
				break;
				case "nvarchar":
				reval = "String";
				break;
				case "real":
				reval = "System.Single";
				break;
				case "smalldatetime":
				reval = "System.DateTime";
				break;
				case "smallint":
				reval = "Int16";
				break;
				case "smallmoney":
				reval = "System.Decimal";
				break;
				case "timestamp":
				reval = "System.DateTime";
				break;
				case "tinyint":
				reval = "System.Byte";
				break;
				case "uniqueidentifier":
				reval = "System.Guid";
				break;
				case "varbinary":
				reval = "System.Byte[]";
				break;
				case "varchar":
				reval = "String";
				break;
				case "Variant":
				reval = "Object";
				break;
				default:
				reval = "String";
				break;
			}
			return reval;
		}

		/// <summary>
		/// 转sql数据库类型
		/// </summary>
		/// <param name="type"></param>
		/// <returns></returns>
		private static string ChangeToSqlType(string type)
		{
			string reval = string.Empty;
			switch (type)
			{
				case "Int32":
				reval = "int";
				break;
				case "String":
				reval = "text";
				break;
				case "Int64":
				reval = "bigint";
				break;
				case "System.Byte[]":
				reval = "binary";
				break;
				case "Boolean":
				reval = "bit";
				break;
				//case "char":
				//reval = "String";
				//break;
				case "System.DateTime":
				reval = "datetime";
				break;
				case "decimal":
				reval = "System.Decimal";
				break;
				case "System.Double":
				reval = "float";
				break;
				//case "System.Byte[]":
				//reval = "image";
				//break;
				case "System.Decimal":
				reval = "money";
				break;
				//case "nchar":
				//reval = "String";
				//break;
				//case "ntext":
				//reval = "String";
				//break;
				//case "numeric":
				//reval = "System.Decimal";
				//break;
				//case "nvarchar":
				//reval = "String";
				//break;
				case "System.Single":
				reval = "real";
				break;
				//case "System.DateTime":
				//reval = "smalldatetime";
				//break;
				case "Int16":
				reval = "smallint";
				break;
				//case "smallmoney":
				//reval = "System.Decimal";
				//break;
				//case "timestamp":
				//reval = "System.DateTime";
				//break;
				case "System.Byte":
				reval = "tinyint";
				break;
				case "System.Guid":
				reval = "uniqueidentifier";
				break;
				//case "varbinary":
				//reval = "System.Byte[]";
				//break;
				//case "varchar":
				//reval = "String";
				//break;
				case "Object":
				reval = "Variant";
				break;
				default:
				reval = "String";
				break;
			}
			return reval;
		}

		/// <summary>
		/// 获得基本的表结构
		/// </summary>
		/// <returns></returns>
		public static DataTable GetBasicTableInfo()
		{
			DataTable dt = new DataTable();
			dt.Columns.Add("fieldName");
			dt.Columns.Add("typeName");
			dt.Columns.Add("typeLength");
			dt.Columns.Add("idField");
			return dt;
		}



		//添加,表名
		public static string CreateInsert(string tableName, Hashtable values)
		{
			DataTable dt = new DataTable();
			//表信息
			dt = CommonProc.GetTableInfo(tableName).Tables[0];
			return CreateInsert(tableName, dt, values);
		}

		//public static string CreateInsert()

		public static string CreateInsert(string tableName, DataTable dt, Hashtable values)
		{

			StringBuilder sql = new StringBuilder();
			//字段
			StringBuilder fieldNames = new StringBuilder();
			//字段值
			StringBuilder fieldValues = new StringBuilder();
			//类型
			string fieldType = "";
			foreach (DataRow dr in dt.Rows)
			{

				#region defence
				//没有请求值
				if (values[dr["fieldName"].ToString()] == null)
				{
					continue;
				}
				//主键
				if (!string.IsNullOrEmpty(dr["idField"].ToString()))
				{
					continue;
				}
				#endregion

				fieldType = dr["typeName"].ToString();

				if ("int,bigint,bit,decimal,float,money,numeric,real,smallint,smallmoney,tinyint".Contains(fieldType.ToLower()))
				{
					//数值
					if (!string.IsNullOrEmpty(values[dr["fieldName"].ToString()].ToString()))
					{
						fieldNames.Append(dr["fieldName"].ToString() + ",");
						fieldValues.Append(values[dr["fieldName"].ToString()] + ",");
					}
				}
				else
				{
					fieldNames.Append(dr["fieldName"].ToString() + ",");
					//字符
					fieldValues.Append("'" + values[dr["fieldName"].ToString()].ToString() + "',");
				}

			}

			CommonTable.RemoveLastChar(ref fieldValues, ',');
			CommonTable.RemoveLastChar(ref fieldNames, ',');

			return sql.Append(string.Format(" insert into {0}({1}) values({2});select @@IDENTITY", tableName, fieldNames, fieldValues)).ToString();
		}


		//修改
		public static string CreateUpdate(string tableName, string sqlWhere, Hashtable values)
		{

			#region 变量


			DataTable dt = new DataTable();
			#endregion

			//表信息
			dt = CommonProc.GetTableInfo(tableName).Tables[0];

			return CreateUpdate(tableName, dt, sqlWhere, values);
		}

		public static string CreateUpdate(string tableName, DataTable dt, string sqlWhere, Hashtable values)
		{

			StringBuilder sql = new StringBuilder();
			//字段
			StringBuilder fieldNames = new StringBuilder();
			//字段值
			StringBuilder fieldValues = new StringBuilder();
			//类型
			string fieldType = "";

			foreach (DataRow dr in dt.Rows)
			{

				#region defence
				//没有请求值
				if (values[dr["fieldName"].ToString()] == null)
				{
					continue;
				}
				//主键
				if (!string.IsNullOrEmpty(dr["idField"].ToString()))
				{
					continue;
				}
				#endregion


				fieldType = dr["typeName"].ToString();

				if ("int,bigint,bit,decimal,float,money,numeric,real,smallint,smallmoney,tinyint".Contains(fieldType.ToLower()))
				{
					//数值
					if (!string.IsNullOrEmpty(values[dr["fieldName"].ToString()].ToString()))
					{
						fieldNames.Append(dr["fieldName"].ToString() + "=" + values[dr["fieldName"].ToString()] + ",");

					}
				}
				else
				{
					//字符
					fieldNames.Append(dr["fieldName"].ToString() + "='" + values[dr["fieldName"].ToString()] + "',");
				}

			}
			CommonTable.RemoveLastChar(ref fieldNames, ',');


			return string.Format("update {0} set {1} where {2}", tableName, fieldNames.ToString(), sqlWhere);
		}



		//查询
		public static string CreateSelect(string tableName, string sqlWhere, string fieldNames = "*")
		{
			return string.Format("select {0} from {1} where {2}", fieldNames, tableName, sqlWhere);
		}

		//删除
		public static string CreateDel(string tableName, string sqlWhere)
		{
			return string.Format(" delete from  {0} where {1}", tableName, sqlWhere);
		}
		#endregion

		#region post方式

		//添加
		public static string CreateInsert(string tableName)
		{
			StringBuilder sql = new StringBuilder();
			//字段
			StringBuilder fieldNames = new StringBuilder();
			//字段值
			StringBuilder fieldValues = new StringBuilder();
			//类型
			string fieldType = "";
			DataTable dt = new DataTable();

			NameValueCollection form = HttpContext.Current.Request.Form;

			dt = CommonProc.GetTableInfo(tableName).Tables[0];

			foreach (DataRow dr in dt.Rows)
			{

				#region defence
				//没有请求值
				if (form[dr["fieldName"].ToString()] == null)
				{

					continue;
				}
				//主键
				if (!string.IsNullOrEmpty(dr["idField"].ToString()))
				{
					continue;
				}
				#endregion

				fieldNames.Append(dr["fieldName"].ToString() + ",");
				fieldType = dr["typeName"].ToString();

				if ("int,bigint,bit,decimal,float,money,numeric,real,smallint,smallmoney,tinyint".Contains(fieldType))
				{
					//数值
					if (!string.IsNullOrEmpty(form[dr["fieldName"].ToString()]))
					{
						fieldValues.Append(form[dr["fieldName"].ToString()] + ",");
					}
				}
				else
				{
					//字符
					fieldValues.Append("'" + form[dr["fieldName"].ToString()] + "',");

				}

			}

			CommonTable.RemoveLastChar(ref fieldValues, ',');
			CommonTable.RemoveLastChar(ref fieldNames, ',');

			return sql.Append(string.Format(" insert into {0}({1}) values({2})", tableName, fieldNames, fieldValues)).ToString();

		}

		#endregion

		#endregion


		#endregion

	}

	public class CommonProc
	{

		#region 获得表信息
		public static DataSet GetTableInfo(string tableName)
		{
			SqlParameter[] p ={
								new SqlParameter("@table",SqlDbType.VarChar,50)
							 };
			p[0].Value = tableName;
			return DbHelperSQL.RunProcedure("pro_getTableInfo", p, tableName);
		}
		#endregion

		#region 分页
		public static DataSet GetRecordByPage(string TableNames, string PrimaryKey, string Fields, int PageSize, int CurrentPage, string Filter, string Group, string Order)
		{
			SqlParameter[] parameters = new SqlParameter[] { 
				new SqlParameter("@TableNames", SqlDbType.VarChar, 500), 
				new SqlParameter("@PrimaryKey", SqlDbType.VarChar, 100), 
				new SqlParameter("@Fields", SqlDbType.VarChar, 0x3e8), 
				new SqlParameter("@PageSize", SqlDbType.Int), 
				new SqlParameter("@CurrentPage", SqlDbType.Int), 
				new SqlParameter("@Filter", SqlDbType.VarChar, 800), 
				new SqlParameter("@Group", SqlDbType.VarChar, 500), 
				new SqlParameter("@Order", SqlDbType.VarChar, 500) 
			};
			parameters[0].Value = TableNames;
			parameters[1].Value = PrimaryKey;
			parameters[2].Value = Fields;
			parameters[3].Value = PageSize;
			parameters[4].Value = CurrentPage;
			parameters[5].Value = Filter;
			parameters[6].Value = Group;
			parameters[7].Value = Order;
			return DbHelperSQL.RunProcedure("pro_general_paging_list", parameters, "ds");
		}
		#endregion

		#region 删除验证

		public static int GetDelStatus(int id, string fieldid, string tbl, string fieldstatus, string status)
		{
			SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("@id", SqlDbType.Int), new SqlParameter("@fieldid", SqlDbType.VarChar, 50), new SqlParameter("@tbl", SqlDbType.VarChar, 50), new SqlParameter("@fieldstatus", SqlDbType.VarChar, 50), new SqlParameter("@status", SqlDbType.VarChar, 50), new SqlParameter("@outResult", SqlDbType.Int) };
			parameters[0].Value = id;
			parameters[1].Value = fieldid;
			parameters[2].Value = tbl;
			parameters[3].Value = fieldstatus;
			parameters[4].Value = status;
			return DbHelperSQL.RunProcedures("pro_status_delete", parameters);
		}
		#endregion

	}

	public class CommonTable
	{

		/// <summary>
		/// 生成唯一键Code
		/// </summary>
		/// <returns></returns>
		public static string BuildCode()
		{
			return Guid.NewGuid().ToString();
		}

		#region 导出excel
		private static StringWriter GetStringWriter(DataTable dt)
		{
			StringWriter sw = new StringWriter();
			//读列名  
			foreach (DataColumn dc in dt.Columns)
				sw.Write(dc.ColumnName + "\t");
			//读列值  
			//重新的一行  
			sw.Write(sw.NewLine);
			if (dt != null)
			{
				foreach (DataRow dr in dt.Rows)
				{
					for (int i = 0; i < dt.Columns.Count; i++)
					{
						sw.Write(dr[i].ToString() + "\t");
					}
					sw.Write(sw.NewLine);
				}
			}
			sw.Close();

			return sw;
		}

		/// <summary>
		/// 导出Excel
		/// </summary>
		/// <param name="dt">数据表</param>
		/// <param name="ExportFileName">文件名</param>
		/// <param name="p">当前页</param>
		public static StringWriter ExcelImport(DataTable dt, string ExportFileName, Page p)
		{
			StringWriter sw = GetStringWriter(dt);
			//当前编码
			HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
			//把输出的文件名进行编码
			//     使用指定的编码对象对 URL 字符串进行编码。

			string fileName = HttpUtility.UrlEncode(ExportFileName, System.Text.Encoding.UTF8);
			//文件名
			string str = "attachment;filename=" + fileName + ".xls";
			//把文件头输出，此文件头激活文件下载框
			HttpContext.Current.Response.AppendHeader("Content-Disposition", str);//http报头文件
			//     获取或设置输出流的 HTTP MIME 类型。

			HttpContext.Current.Response.ContentType = "application/ms-excel";
			//     获取或设置一个值，该值指示当前页请求结束时该页是否保持其视图状态以及它包含的任何服务器控件的视图状态。
			p.EnableViewState = false;
			//p.Response.Write(sw);
			//p.Response.End();
			return sw;
		}

		#endregion



		#region TxtWrite	把字符variable值输出到文本文件,用于调试.
		public static string filePath = "C:\\debug.txt";
		public static void DebugInfo(string value)
		{
			//string tempStr = File.ReadAllText(filePath);

			File.AppendAllText(filePath, DateTime.Now.ToString() + "\r\n");

			File.AppendAllText(filePath, value + "\r\n");
			//System.Diagnostics.Process.Start(filePath);
		}
		#endregion

		#region 简化.net方法名
		//字符串是否可用
		public bool StrPass(string str)
		{
			return !string.IsNullOrEmpty(str);
		}
		#endregion

		#region 错误日志

		/// <summary>
		/// 创建日志
		/// </summary>
		/// <typeparam name="T">实体类</typeparam>
		/// <param name="ex">异常类</param>
		/// <param name="t">实体类对象</param>
		/// <param name="path">路径</param>
		/// <returns>返回日志文件路径</returns>
		public static string CreateLog<T>(Exception ex, T t, string path = "", NameValueCollection form = null)
		{
			if (string.IsNullOrEmpty(path))
			{
				path = HttpContext.Current.Server.MapPath("~");
			}
			if (!Directory.Exists(path + "log"))
			{
				//创建日志文件夹
				Directory.CreateDirectory(path + "log");
			}
			//发生异常每天都创建一个单独的日子文件[*.log],每天的错误信息都在这一个文件里。方便查找
			WriteLogInfo(ex, path + "log\\" + DateTime.Now.ToString("yy-MM-dd") + ".log", t, form);
			return path + "log\\" + DateTime.Now.ToString("yy-MM-dd") + ".log";
		}

		/// <summary>
		/// 向日志文件中追加实体数据
		/// </summary>
		/// <typeparam name="T">实体类</typeparam>
		/// <param name="path">路径</param>
		/// <param name="t">实体类对象</param>
		public static void WriteLogInfo<T>(string path, T t)
		{
			using (StreamWriter sw = new StreamWriter(path, true, Encoding.Default))
			{
				sw.WriteLine("【ModelData】\n" + SetFormToModel<T>.ModelValue(t));
				sw.WriteLine();
			}
		}


		/// <summary>
		/// 错误信息输出
		/// </summary>
		/// <typeparam name="T">实体类</typeparam>
		/// <param name="ex">异常类</param>
		/// <param name="path">路径</param>
		/// <param name="t">实体类对象</param>
		private static void WriteLogInfo<T>(Exception ex, string path, T t, NameValueCollection form = null)
		{
			using (StreamWriter sw = new StreamWriter(path, true, Encoding.Default))
			{
				sw.WriteLine("-----------------------------------------【"
							   + DateTime.Now.ToLongTimeString()
							   + "】-----------------------------------------");
				if (ex != null)
				{
					sw.WriteLine("【ErrorType】" + ex.GetType());
					sw.WriteLine("【TargetSite】" + ex.TargetSite);
					sw.WriteLine("【Message】" + ex.Message);
					sw.WriteLine("【Source】" + ex.Source);
					sw.WriteLine("【StackTrace】" + ex.StackTrace);
					sw.WriteLine("【ModelData】");
					sw.WriteLine(SetFormToModel<T>.ModelValue(t, form));
				}
				else
				{
					sw.WriteLine("Exception is NULL");
				}
				sw.WriteLine();
			}
		}

		/// <summary>
		/// 创建日志文件
		/// </summary>
		/// <param name="ex">异常类</param>
		public static void CreateLog(Exception ex, string path = "")
		{
			if (string.IsNullOrEmpty(path))
			{
				path = HttpContext.Current.Server.MapPath("~");
			}
			if (!Directory.Exists(path + "log"))
			{
				//创建日志文件夹
				Directory.CreateDirectory(path + "log");
			}
			//发生异常每天都创建一个单独的日子文件[*.log],每天的错误信息都在这一个文件里。方便查找
			WriteLogInfo(ex, path + "log\\" + DateTime.Now.ToString("yy-MM-dd") + ".log");
		}

		/// <summary>
		/// 写日志信息
		/// </summary>
		/// <param name="ex">异常类</param>
		/// <param name="path">日志文件存放路径</param>
		private static void WriteLogInfo(Exception ex, string path)
		{
			using (StreamWriter sw = new StreamWriter(path, true, Encoding.Default))
			{
				sw.WriteLine("-----------------------------------------【"
							   + DateTime.Now.ToLongTimeString()
							   + "】-----------------------------------------");
				if (ex != null)
				{
					sw.WriteLine("【ErrorType】" + ex.GetType());
					sw.WriteLine("【TargetSite】" + ex.TargetSite);
					sw.WriteLine("【Message】" + ex.Message);
					sw.WriteLine("【Source】" + ex.Source);
					sw.WriteLine("【StackTrace】" + ex.StackTrace);
				}
				else
				{
					sw.WriteLine("Exception is NULL");
				}
				sw.WriteLine();
			}
		}

		//日期有效性检查.
		public static DateTime DateCheck(DateTime date)
		{
			if (date == DateTime.Parse("0001/1/1 星期一 0:00:00"))
			{
				//数据库最小日期值
				return DateTime.Parse("1/1/1753 12:00:00 ");
			}
			else
			{
				return date;
			}
		}
		#endregion

		#region 数据集操作
		/// <summary>
		/// 移除指定的列
		/// </summary>
		/// <param name="ds">数据集</param>
		/// <param name="columnName">列名集,用','做为分割符.</param>
		/// <param name="remove">保留还是移除,默认为移除.</param>
		public static void RemoveColumn(ref DataSet ds, string columnName, bool remove = true)
		{
			StringBuilder removeColumnNames = new StringBuilder();
			StringBuilder keepColumnNames = new StringBuilder();
			StringBuilder columnNames = new StringBuilder();
			for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
			{
				if (columnName.Contains(ds.Tables[0].Columns[i].ColumnName))
				{
					removeColumnNames.Append(ds.Tables[0].Columns[i].ColumnName + ",");
				}
				else
				{
					keepColumnNames.Append(ds.Tables[0].Columns[i].ColumnName + ",");
				}


				//if (remove)
				//{
				//    //移除
				//    if (columnName.Contains(ds.Tables[0].Columns[i].ColumnName))
				//    {
				//        columnNames.Append(ds.Tables[0].Columns[i].ColumnName + ",");
				//    }
				//}
				//else {
				//    //保留
				//    if (!columnName.Contains(ds.Tables[0].Columns[i].ColumnName))
				//    {
				//        columnNames.Append(ds.Tables[0].Columns[i].ColumnName + ",");
				//    }
				//}
			}
			columnNames = remove ? removeColumnNames : keepColumnNames;
			CommonTable.RemoveLastChar(ref columnNames, ',');
			foreach (string s in columnNames.ToString().Split(','))
			{
				ds.Tables[0].Columns.Remove(s);
			}
		}
		/// <summary>
		/// 列标题设置
		/// </summary>
		/// <param name="dt">数据集</param>
		/// <param name="tableName">表名</param>
		public static void ColumnCaptionSet(ref DataSet ds, string tableName)
		{
			DataTable explainDt = new DataTable();
			explainDt = GetColumnExplain(tableName).Tables[0];
			foreach (DataRow r in explainDt.Rows)
			{
				if (ds.Tables[0].Columns.Contains(r[0].ToString()))
				{
					ds.Tables[0].Columns[r[0].ToString()].Caption = r[1].ToString();
				}
			}
		}
		/// <summary>
		/// 得到列的说明信息
		/// </summary>
		/// <param name="tableName">表名</param>
		/// <param name="schema">架构(默认为'dbo')</param>
		/// <returns></returns>
		public static DataSet GetColumnExplain(string tableName, string schema = "dbo")
		{
			return DbHelperSQL.Query(string.Format("SELECT objname,value FROM fn_listextendedproperty (NULL, 'schema', '{0}', 'table', '{1}', 'column', default)", schema, tableName));
		}
		#endregion

		#region 文件操作
		/// <summary>
		/// 批量生成文档文件
		/// </summary>
		/// <param name="TextName">文件名集合(不需要txt扩展名)</param>
		/// <param name="filePath">路径</param>
		public static void createTextFile(string TextName, string filePath)
		{
			//没有加\
			if (filePath.LastIndexOf('\\') != filePath.Length - 1)
			{
				filePath += "\\";
			}
			for (int i = 0; i < TextName.Split(',').Length; i++)
			{
				File.AppendAllText(filePath + TextName.Split(',')[i] + ".txt", "");
			}
		}
		/// <summary>
		/// 得到指定扩展名的文件名集合
		/// </summary>
		/// <param name="filePath">路径</param>
		/// <param name="extendName">扩展名</param>
		/// <param name="removeExtend">是否保留扩展名</param>
		/// <returns>文件名集合</returns>
		public static string scanFileName(string filePath, string extendName, bool removeExtend = true)
		{
			string[] filecollect = Directory.GetFileSystemEntries(filePath);
			StringBuilder fileNames = new StringBuilder();
			string fileName;
			foreach (string file in filecollect)
			{
				fileName = file.Substring(file.LastIndexOf("\\") + 1);
				if (!fileName.Contains("."))
				{
					continue;
				}
				if (fileName.Substring(fileName.LastIndexOf('.')).Equals(extendName))
				{
					fileNames.Append(fileName + ",");
				}
			}
			if (removeExtend)
			{
				//去扩展名
				fileNames.Replace(extendName, "");
			}
			return fileNames.ToString();
		}
		//读取文本文件,返回每一行用指定分隔符分割的字符串
		public static string explain(string filePath, char division)
		{
			FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read);
			StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("gb2312"));
			reader.BaseStream.Seek(0L, SeekOrigin.Begin);
			StringBuilder temp = new StringBuilder();
			string tempS;
			for (int i = 0; reader.Peek() > -1; i++)
			{
				tempS = reader.ReadLine();
				if (!string.IsNullOrEmpty(tempS))
				{
					temp.Append(tempS + division);
				}
			}
			reader.Close();
			return temp.ToString();
		}
		#endregion

		#region 查询

		#region 查询基础单元
		/// <summary>
		/// 增加单个日期字段的区间判断条件
		/// </summary>
		/// <param name="sqlWhere">要加条件的sql语句</param>
		/// <param name="first">字段名</param>
		/// <param name="firstValue">第一个值</param>
		/// <param name="secondValue">第二个值</param>
		public static void OnlyDateContrast(ref string sqlWhere, string fieldName, string firstValue, string secondValue)
		{
			string linkStr = Alternative(sqlWhere, fieldName, " or , and ");
			if (!string.IsNullOrEmpty(firstValue) && string.IsNullOrEmpty(secondValue))
				//只有最小数值
				sqlWhere += string.Format(linkStr + fieldName + ">='{0}'", firstValue);
			else if (!string.IsNullOrEmpty(secondValue) && string.IsNullOrEmpty(firstValue))
				//只有最大数值
				sqlWhere += string.Format(linkStr + fieldName + "<='{0}'", secondValue);
			else if (!string.IsNullOrEmpty(firstValue) && !string.IsNullOrEmpty(secondValue))
			{
				//完整的数值区间
				//调整数值顺序
				if (DateTime.Parse(firstValue) > DateTime.Parse(secondValue))
				{

					sqlWhere += string.Format(linkStr + fieldName + " between '{0}' and '{1}'", secondValue, firstValue);
				}
				else
				{
					sqlWhere += string.Format(linkStr + fieldName + "  between '{0}' and '{1}'", firstValue, secondValue);
				}
			}

		}


		/// <summary>
		/// 增加单个数字字段的区间判断条件
		/// </summary>
		/// <param name="sqlWhere">要加条件的sql语句</param>
		/// <param name="first">字段名</param>
		/// <param name="firstValue">第一个值</param>
		/// <param name="secondValue">第二个值</param>
		public static void TwoIntContrast(ref string sqlWhere, string fieldName, string firstValue, string secondValue)
		{
			string linkStr = Alternative(sqlWhere, fieldName, " or , and ");
			if (!string.IsNullOrEmpty(firstValue) && string.IsNullOrEmpty(secondValue))
				//只有最小数值
				sqlWhere += string.Format(linkStr + fieldName + ">={0}", Convert.ToInt32(firstValue));
			else if (!string.IsNullOrEmpty(secondValue) && string.IsNullOrEmpty(firstValue))
				//只有最大数值
				sqlWhere += string.Format(linkStr + fieldName + "<={0}", Convert.ToInt32(secondValue));
			else if (!string.IsNullOrEmpty(firstValue) && !string.IsNullOrEmpty(secondValue))
			{
				//完整的数值区间
				//调整数值顺序
				if (Convert.ToInt32(firstValue) > Convert.ToInt32(secondValue))
				{
					sqlWhere += string.Format(linkStr + fieldName + " between {0} and {1}", Convert.ToInt32(secondValue), Convert.ToInt32(firstValue));
				}
				else
				{
					sqlWhere += string.Format(linkStr + fieldName + "  between {0} and {1}", Convert.ToInt32(firstValue), Convert.ToInt32(secondValue));
				}

			}

		}

		/// <summary>
		/// 增加单个字符字段的相等或Like判断条件
		/// </summary>
		/// <param name="sqlWhere">要加条件的sql语句</param>
		/// <param name="field">字段名</param>
		/// <param name="fieldValue">第一个值</param>
		/// <param name="like">是否使用like</param>
		public static void OnlyOneString(ref string sqlWhere, string fieldName, string fieldValue, bool like = true)
		{
			string linkStr = Alternative(sqlWhere, fieldName, " or , and ");
			if (!string.IsNullOrEmpty(fieldValue))
			{
				switch (like)
				{
					case true:
					sqlWhere += linkStr + fieldName + " like '%" + fieldValue + "%'";
					break;
					case false:
					sqlWhere += linkStr + fieldName + " = '" + fieldValue + "'";
					break;
				}

			}


		}
		/// <summary>
		/// 增加单个日期字段的相等或Like判断条件
		/// </summary>
		/// <param name="sqlWhere">要加条件的sql语句</param>
		/// <param name="field">字段名</param>
		/// <param name="fieldValue">第一个值</param>
		/// <param name="like">是否使用like</param>
		public static void OnlyOneDate(ref string sqlWhere, string fieldName, string fieldValue, bool like = true)
		{
			string linkStr = Alternative(sqlWhere, fieldName, " or , and ");
			if (!string.IsNullOrEmpty(fieldValue))
			{
				switch (like)
				{
					case true:
					sqlWhere += linkStr + fieldName + " like '%" + fieldValue + "%'";
					break;
					case false:
					sqlWhere += string.Format(" and convert(char(10),{0},120)= '{1}'", fieldName, fieldValue);
					break;
				}
			}
		}
		/// <summary>
		/// 增加单个数字字段的相等判断条件
		/// </summary>
		/// <param name="sqlWhere">要加条件的sql语句</param>
		/// <param name="field">字段名</param>
		/// <param name="fieldValue">值</param>
		public static void OnlyOneInt(ref string sqlWhere, string fieldName, string fieldValue)
		{

			//---------------------谢俊---2013.9.29 8:42---------------------
			// 功能描述：过滤处于删除状态的记录
			string linkStr = " and ";
			if (!fieldName.Contains("status"))
			{
				linkStr = Alternative(sqlWhere, fieldName, " or , and ");
			}
			//--------------------------------------------------------------------


			if (!string.IsNullOrEmpty(fieldValue))
			{
				sqlWhere += linkStr + fieldName + " = " + Convert.ToInt32(fieldValue);
			}


		}


		/// <summary>
		/// 数值集合查询
		/// </summary>
		/// <param name="sqlWhere"></param>
		/// <param name="field"></param>
		/// <param name="fieldValue"></param>
		public static void OnlyOneIntIn(ref string sqlWhere, string fieldName, string fieldValue)
		{

			if (string.IsNullOrEmpty(fieldValue) || string.IsNullOrEmpty(fieldName))
			{
				return;
			}

			if (!fieldValue.Contains(','))
			{
				//没有逗号,全等查询.
				OnlyOneInt(ref sqlWhere, fieldName, fieldValue);
				return;
			}
			//---------------------谢俊---2013.9.29 8:42---------------------
			// 功能描述：过滤处于删除状态的记录
			string linkStr = " and ";
			if (!fieldName.Contains("status"))
			{
				linkStr = Alternative(sqlWhere, fieldName, " or , and ");
			}
			//--------------------------------------------------------------------
			if (!string.IsNullOrEmpty(fieldValue))
			{
				//sqlWhere += linkStr + fieldName + " in(" + string.Join(",", fieldValue.Split(',')) + ") ";
				sqlWhere += linkStr + fieldName + " in(" + fieldValue + ") ";
			}

		}

		/// <summary>
		/// 字符集合查询
		/// </summary>
		/// <param name="sqlWhere"></param>
		/// <param name="field"></param>
		/// <param name="fieldValue"></param>
		public static void OnlyOneStringIn(ref string sqlWhere, string fieldName, string fieldValue)
		{
			string linkStr = Alternative(sqlWhere, fieldName, " or , and ");
			StringBuilder temps = new StringBuilder();
			foreach (var item in fieldValue.Split(','))
			{
				temps.Append("'" + item + "',");
			}
			string temp = temps.ToString();
			RemoveLastChar(ref temp, ',');
			temps.Append(temp);
			if (!string.IsNullOrEmpty(fieldValue))
			{
				sqlWhere += linkStr + fieldName + " in(" + temps.ToString() + ") ";
			}

		}
		#endregion

		#region 单一字段查询


		//功能描述:
		/*
		 *1,传进实体类,字段名,值,查询类型(字符全等,字符like,字符in,数值in,数值区间,数值全等).
		 *2,字段名,程序根据此字段名获得字段类型(数据库字段类型)
		 *3,根据查询类型参数,生成sql查询语句.
		 *4,区间用'-'分割.
		//注意事项:
		 * 1,字符类型则值要加上引号
		 * 2,数值没有like
		 * 3,字符没有区间		 		 
		 */
		/// <summary>
		/// 单一字段查询
		/// </summary>
		/// <param name="sqlWhere">Sql语句</param>
		/// <param name="name">字段名</param>
		/// <param name="value">值</param>
		/// <param name="searchType">查询类型:
		/// in:集合查询(暂时只支持数值)
		/// like:字符模糊查询(只支持字符)
		/// =:全等查询(暂时只支持数值)
		/// between:区间查询(支持数值与日期)
		/// </param>
		/// <param name="DataType">数据类型:
		/// String:日期区间使用此类型
		/// Int:默认值
		/// </param>
		public static void OnlySearch(ref string sqlWhere, string name, string value, string searchType, string DataType = "Int")
		{
			/*
			 *1,字符也可以使用in.
			 *2,字符也可以全等.
			 *3,程序有一定的智能,带分析功能.如:大于100,7月份,昨天,后天,3月前.
			 */
			StringBuilder SearchSql = new StringBuilder();
			//string tempstr = string.Empty;
			switch (searchType)
			{
				case "in":
				#region 集合查询

				//集合查询
				if (DataType == "Int")
				{
					OnlyOneIntIn(ref sqlWhere, name, value);
				}
				else
				{
					OnlyOneStringIn(ref sqlWhere, name, value);
				}
				break;
				#endregion
				case "like":
				#region 模糊查询(包含字符的全等查询)

				//待优化
				//---------------------谢俊---2013.8.27 20:26---------------------
				string linkStr = Alternative(sqlWhere, name, " or , and ");
				// 功能描述：字符可全等查询
				if (value.Substring(0, 1) == "=")
				{

					value = value.Remove(0, 1);
					SearchSql.Append(linkStr + name + " ='" + value + "'");
				}
				else
				{
					//like模糊查询
					SearchSql.Append(linkStr + name + " like'%" + value + "%'");
				}
				//--------------------------------------------------------------------
				break;
				#endregion
				case "between":
				#region 区间查询

				//支持颠倒查询.
				//区间查询,数值:大于100,小于100.日期:2013/7/8之前,之后.
				string[] valueArr = value.Split('|');
				if (DataType == "Int")
				{
					//数值,可应用与金额,数量查询.
					//大于100
					//100-
					//小于100
					//-100
					TwoIntContrast(ref sqlWhere, name, valueArr[0], valueArr[1]);
				}
				else
				{
					//日期
					OnlyDateContrast(ref sqlWhere, name, valueArr[0], valueArr[1]);
				}
				break;
				#endregion
				case "=":
				#region 全等查询

				//全等查询
				if (DataType == "Int")
				{
					OnlyOneInt(ref sqlWhere, name, value);
				}
				else
				{
					OnlyOneDate(ref sqlWhere, name, value, false);
				}
				break;
				#endregion
			}
			//SearchSql.Append(tempstr);
			sqlWhere += SearchSql.ToString();
		}

		/// <summary>
		/// 数值查询
		/// </summary>
		/// <param name="sqlWhere">sql语句</param>
		/// <param name="name">字段名</param>
		/// <param name="value">值</param>
		/// <param name="SearchType">查询类型:Int或String</param>
		public static void IntSearch(ref string sqlWhere, string name, string value, string SearchType = "Int")
		{
			//中文字符去除,待完善.
			Regex oRegex = new Regex(@"[\u4E00-\u9FA5\-]*");
			//Regex oRegex = new Regex(@"[^\d\r\n]*");
			if (value.Contains("|"))
			{
				//区间
				OnlySearch(ref sqlWhere, name, value, "between", SearchType);
			}
			else if (value.Contains("大于") || value.Contains("之前") || value.Contains(">"))
			{
				if (SearchType == "Int")
				{
					value = oRegex.Replace(value, "");
				}
				if (value.Substring(0, 1) == ">")
				{
					value = value.Remove(0, 1);
				}

				//大
				OnlySearch(ref sqlWhere, name, value + "|", "between", SearchType);
			}
			else if (value.Contains("小于") || value.Contains("之后") || value.Contains("<"))
			{
				if (SearchType == "Int")
				{
					value = oRegex.Replace(value, "");
				}
				if (value.Substring(0, 1) == "<")
				{
					value = value.Remove(0, 1);
				}
				//小
				OnlySearch(ref sqlWhere, name, "|" + value, "between", SearchType);
			}
			else
			{
				if (SearchType == "Int")
				{
					value = oRegex.Replace(value, "");
				}
				if (value.Substring(0, 1) == "=")
				{
					value = value.Remove(0, 1);
				}
				//全等
				OnlySearch(ref sqlWhere, name, value, "=", SearchType);
			}
		}
		/// <summary>
		/// 状态查询
		/// </summary>
		/// <param name="sqlWhere">sql语句</param>
		/// <param name="name">字段名</param>
		/// <param name="value">值</param>
		/// <param name="Status">字符对应数值的字符串."离,0|在,1|请,2|假,2"</param>
		public static void StatusSearch(ref string sqlWhere, string name, string value, string Status)
		{
			//得到字符对应的数值
			string stemp = string.Join(",", StoInt(value, Status)).Replace("-1,", "");
			//移除最后一个字符
			CommonTable.RemoveLastChar(ref stemp, ',');
			CommonTable.OnlySearch(ref sqlWhere, name, stemp, "in", "Int");
		}
		#endregion
		/// <summary>
		/// 如果字符串中已经包含指定的字符,则返回第一个值,否则第二个值.
		/// </summary>
		/// <param name="value">要判断的字符串</param>
		/// <param name="condition">字符</param>
		/// <param name="returnValue">返回值使用逗号分隔</param>
		/// <returns></returns>
		public static string Alternative(string value, string condition, string returnValue)
		{
			string[] tempArr = returnValue.Split(',');
			return value.Contains(condition) ? tempArr[0] : tempArr[1];
		}
		#region 高级查询	待优化:异常处理,字符前导空格,特殊字符屏蔽.

		/// <summary>
		/// 查询通用版
		/// </summary>
		/// <typeparam name="T">实体类</typeparam>
		/// <param name="t">实体类实例</param>
		/// <param name="sqlWhere">要添加条件的Sql语句</param>
		/// <param name="name">字段名,多个字段名的话用'|'分割.</param>
		/// <param name="value">字段名对应的值,要与字段名相对应,用'|'分割.</param>
		/// <param name="StoInt">字符对应数值的字符串,主要应用于状态,类型字段,解决查询值与数据库实际值不符的问题.
		/// 规则:"离,0|在,1|请,2|假,2"</param>
		/// <returns>返回"1"则执行成功,否则返回错误信息.</returns>
		public static string PonlySearch<T>(T t, ref string sqlWhere, string nameStr, string valueStr, string StoInt = "")
		{
			if (string.IsNullOrEmpty(valueStr))
			{
				return "Search value is null";
			}
			try
			{
				#region variable初始化
				//-------分类后的字段集合---分为数值,日期,字符,状态(特殊字段)四种类型---------
				string[] FieldNameArr = SetFormToModel<T>.GetFieldNameCollection(t).Split('|');
				//----------------------------------------------------------------------------
				string value = valueStr;
				string name = nameStr;
				RemoveLastChar(ref name, '|');
				RemoveLastChar(ref value, '|');
				//字段名集合
				string[] fieldNameArr = name.Split('|');
				//查询值集合
				string[] fieldValueArr = value.Split('|');
				//字段类型,数值,日期,字符,状态.
				string nameType = "String";
				#endregion
				for (int u = 0; u < fieldNameArr.Length; u++)
				{
					#region 类型判断
					if (FieldNameArr[0].Contains(fieldNameArr[u].ToLower()))
					{
						//数值类型执行相同的查询.
						nameType = "Int";
					}
					else if (FieldNameArr[1].Contains(fieldNameArr[u].ToLower()))
					{
						//状态
						nameType = "Status";
					}
					else if (FieldNameArr[2].Contains(fieldNameArr[u].ToLower()))
					{
						//字符
						nameType = "String";
					}
					else if (FieldNameArr[3].Contains(fieldNameArr[u].ToLower()))
					{
						//日期
						nameType = "Date";
					}
					#endregion
					#region 查询条件
					switch (nameType)
					{
						case "Status":
						#region 状态字段,也可是特殊字段
						//状态
						CommonTable.StatusSearch(ref sqlWhere, fieldNameArr[u], fieldValueArr[u], StoInt);
						break;
						#endregion
						case "Int":
						#region 数值字段
						//---------------------谢俊---2013.8.24 12:36---------------------
						// 功能描述：数值区间的分隔符改用'|'.
						fieldValueArr[u] = fieldValueArr[u].Replace("-", "|");



						//--------------------------------------------------------------------
						//数值
						CommonTable.IntSearch(ref sqlWhere, fieldNameArr[u], fieldValueArr[u]);
						break;
						#endregion
						case "Date":
						#region 日期字段
						if (fieldValueArr[u].Contains(".") && !fieldValueArr[u].Contains("-"))
						{
							fieldValueArr[u] = fieldValueArr[u].Replace(".", "-");
						}
						//---------------------谢俊---2013.8.24 13:41---------------------
						// 功能描述：日期区间改用'|'分割.
						if (fieldValueArr[u].Contains("-") && !fieldValueArr[u].Contains("/"))
						{
							string[] valueArr = fieldValueArr[u].Split('-');
							for (int i = 1; i < valueArr.Length; i++)
							{
								if (valueArr[i].Length == 4)
								{
									valueArr[i] = "|" + valueArr[i];
									fieldValueArr[u] = string.Join("/", valueArr);
									fieldValueArr[u] = fieldValueArr[u].Remove(fieldValueArr[u].IndexOf("|") - 1, 1);
									break;
								}
							}
						}
						else if (fieldValueArr[u].Contains("/") && fieldValueArr[u].Contains("-"))
						{
							string[] tempArr = fieldValueArr[u].Split('-');
							if (tempArr[1].Split('/')[0].Length == 4)
							{
								fieldValueArr[u] = fieldValueArr[u].Replace("-", "|");
							}
						}

						//--------------------------------------------------------------------
						if (fieldValueArr[u].Contains("至"))
						{
							fieldValueArr[u] = fieldValueArr[u].Replace("至", "|");
						}
						//时间				
						CommonTable.IntSearch(ref sqlWhere, fieldNameArr[u], fieldValueArr[u], "String");
						break;
						#endregion
						default:
						#region 字符字段
						//字符
						CommonTable.OnlySearch(ref sqlWhere, fieldNameArr[u], fieldValueArr[u], "like");
						break;
						#endregion
					}
					#endregion
				}
				//DebugInfo(sqlWhere);
				#region sql查询优化
				sqlWhere = CommonTable.SqlWhereCorrection(sqlWhere, nameStr);
				#endregion
				return "1";
			}
			catch (Exception e)
			{

				return e.Message;
			}

		}
		#endregion

		#endregion

		#region 数组操作
		/// <summary>
		/// 数组排序
		/// </summary>
		/// <param name="arr">数组</param>
		public static void SelectSort(int[] arr)
		{
			//遍历数组,此数组会越来越小,每次都会有最小值,[0]小标每次下移.
			for (int i = 0; i < arr.Length - 1; i++)
			{

				//用于存储最小数值
				int minIndex = i;
				//从下往上遍历,每次得到最小值.
				for (int j = arr.Length - 1; j > i; j--)
				{
					//小于
					if (arr[j] < arr[minIndex])
					{
						//存储最小值
						minIndex = j;
					}
				}
				//把最小值放到数组的第一个下标
				convert(ref arr[i], ref arr[minIndex]);
			}
		}

		/// <summary>
		/// 数值替换
		/// </summary>
		/// <param name="a"></param>
		/// <param name="b"></param>
		public static void convert(ref int a, ref int b)
		{
			int temp = 0;
			temp = a;
			a = b;
			b = temp;
		}
		//删除数组元素
		public static void DeleteE(ref int[] arr, string value)
		{
			//int[] arrtemp
			//string[] temparr;
			//temparr = string.Join(",", arr).Replace(value+",", "").Split(',');
			//arr = Converter<temparr, arrtemp>(string[] temparr);

		}
		//移除数组重复项
		public static String[] RemoveDup(String[] myData)
		{
			if (myData.Length > 0)
			{
				Array.Sort(myData); //先对数组进行排序
				int size = 1; //定义删除重复项后的数组长度 
				for (int i = 1; i < myData.Length; i++)
				{
					if (myData[i] != myData[i - 1])
						size++;
				}
				String[] myTempData = new String[size];
				int j = 0;

				myTempData[j++] = myData[0];

				for (int i = 1; i < myData.Length; i++) //遍历数组成员 
					if (myData[i] != myData[i - 1]) //如果相邻的两个不相等则放入新数组
						myTempData[j++] = myData[i];

				return myTempData;
			}

			return myData;
		}

		public static string[] GetString(string[] values)
		{
			List<string> list = new List<string>();
			//遍历数组成员
			for (int i = 0; i < values.Length; i++)
			{
				//对每个成员做一次新数组查询如果没有相等的则加到新数组
				if (list.IndexOf(values[i].ToLower()) == -1)
					list.Add(values[i]);

			}

			return list.ToArray();
		}
		#endregion

		#region 字符操作
		//日期分析
		public static void DateAnalysis(ref string date)
		{
			/*				 
			 * 1,2013-2014
			 * 2,2013-08-22-25
			 * 3,2013-07-2013-08.
			 * 20130822
			 * 130822
			 * 1308-140822
			 * 字符串“2/14/2007 5:32:00 -7:00”定义的时间比 UTC 早七个小时。
			 */
			date = date.Replace("-", "/");
			StringBuilder newDate = new StringBuilder();
			string[] dateArr = date.Split('-');
			if (dateArr[0].Length == 4 && dateArr[3].Length == 4)
			{

			}
			foreach (string d in dateArr)
			{
				if (d.Length == 4)
				{
					newDate.Append(d + "/");
				}
			}
			if ((date.Contains("年") && date.Contains("月")) && (date.Contains("日") || date.Contains("号")))
			{
				date = DateTime.Parse(date).ToString();
				return;
			}
		}

		/// <summary>
		/// 字符截取
		/// 字符规则a:b,c:d,e:f.
		/// </summary>
		/// <param name="cuted">要截取的字符</param>
		/// <param name="identify">唯一的前导字符,如:'a:'.</param>
		/// <param name="division">分隔符,如:','.</param>
		/// <returns></returns>
		public static string Scut(string cuted, string identify, char division)
		{
			string cutValue = string.Empty;
			string[] cutArr = cuted.Split(division);
			foreach (string i in cutArr)
			{
				if (i.StartsWith(identify))
				{
					//清除不要的值
					cutValue = i.Replace(identify, "");
					break;
				}
			}
			return cutValue;
		}

		/// <summary>
		/// 返回指定字符在字符串中的位置
		/// </summary>
		/// <param name="Svalue">字符串</param>
		/// <param name="Resolved">字符与对应数值,两者用','分割,多个字符则用'|'分割.</param>
		/// <returns>返回经过排序的数组,数组的顺序即字符在字符串中位置.</returns>
		public static int[] StoInt(string Svalue, string Resolved)
		{
			string[] tempArr = Resolved.Split('|');
			int result=0;
			//2013-12-2 20:50:10 字符
			if (!int.TryParse(tempArr[0].Split(',')[1], out result))
			{ 
				


			}






			string resolve = string.Empty;
			int[] indexarr = new int[tempArr.Length];
			for (int i = 0; i < tempArr.Length; i++)
			{
				indexarr[i] = Svalue.Trim().Equals(tempArr[i].Split(',')[0].Trim()) ? 1 : -1;
				resolve += indexarr[i] + "," + int.Parse(tempArr[i].Split(',')[1]) + "|";
			}
			if (resolve.LastIndexOf('|') == resolve.Length - 1)
			{
				resolve = resolve.Remove(resolve.Length - 1, 1);
			}
			SelectSort(indexarr);
			for (int i = 0; i < indexarr.Length; i++)
			{
				if (indexarr[i] != -1)
				{
					for (int e = 0; e < resolve.Split('|').Length; e++)
					{
						if (indexarr[i] == int.Parse(resolve.Split('|')[e].Split(',')[0]))
						{
							indexarr[i] = int.Parse(resolve.Split('|')[e].Split(',')[1]);
							break;
						}
					}
				}

			}
			return indexarr;
		}

		/// <summary>
		/// 移除最后的字符
		/// </summary>
		/// <param name="Value">要移除的字符串</param>
		/// <param name="RemoveChar">要移除的字符</param>
		public static void RemoveLastChar(ref string Value, char RemoveChar)
		{
			if (Value.LastIndexOf(RemoveChar) == Value.Length - 1)
			{
				Value = Value.Remove(Value.Length - 1, 1);
			}
		}

		public static void RemoveLastChar(ref StringBuilder Value, char RemoveChar)
		{
			if (Value.ToString().LastIndexOf(RemoveChar) == Value.Length - 1)
			{
				Value = Value.Remove(Value.Length - 1, 1);
			}
		}

		#endregion

		/*
		 * 1,表名
		 * 2,使用where 1=2,获得表结构
		 * 3,遍历列,对表中的列按类型进行分组.四种类型:字符,数值,日期,状态(查询值是字符,
		 * 数据值是数值,需要进行转换)).
		 * 
		 * 参数:表名,字段名,值,特殊字段(如状态,单据类型.规则:[字段名]字符,数值|字符,数值
		 * [字段名]字符,数值|字符,数值.以此类推)
		 * 
		 * 
		 * 
		 */
		/// <summary>
		///	查询
		/// </summary>
		/// <param name="tableName">表名</param>
		/// <param name="fieldName">字段名(多字段使用'|'分割)</param>
		/// <param name="fieldValue">值(使用'|'分割)</param>
		/// <param name="specialField">特殊字段(要进行字符与数值转换的,
		/// [字段名]字符,数值|字符,数值[字段名]字符,数值|字符,数值)</param>
		/// <param name="sqlWhere">要添加条件的where子句</param>
		public static void PonlySearch(string tableName, string fieldName, string fieldValue, string specialField, ref string sqlWhere)
		{

			#region defense
			if (string.IsNullOrEmpty(tableName))
			{
				return;
			}
			if (string.IsNullOrEmpty(fieldName))
			{
				return;
			}
			if (string.IsNullOrEmpty(fieldValue))
			{
				return;
			}
			if (string.IsNullOrEmpty(sqlWhere))
			{
				sqlWhere += "1=1 ";
			}
			#endregion

			#region variable
			//字段名
			string[] fieldNameArr = fieldName.Split('|');
			//字段值
			string[] fieldValueArr = fieldValue.Split('|');
			string[] specialFieldArr = { };
			if (!string.IsNullOrEmpty(specialField))
			{
				//特殊字段
				specialFieldArr = specialField.Split('[');
			}

			//查询类型
			string searchType;
			//获得表结构
			DataTable dt = DbHelperSQL.Query(string.Format("select * from {0} where  {1}", tableName, "1=2")).Tables[0];
			//索引
			int index = 0;
			//字符转换为数值的规则
			string StoInt = "";
			#endregion

			//遍历字段名
			foreach (string fName in fieldNameArr)
			{
				if (string.IsNullOrEmpty(fName))
				{
					continue;
				}
				//判断当前字段名是否为特殊字段
				if (specialField.Contains(fName))
				{
					//为特殊字段
					searchType = "specialField";
				}
				else
				{
					if (dt.Columns.IndexOf(fName) == -1)
					{
						//没有此列名,结束此次遍历.
						continue;
					}
					//数据类型名
					searchType = dt.Columns[fName].DataType.Name;
				}
				if (searchType.Equals("specialField"))
				{

					#region defence
					if (specialFieldArr.Length == 0)
					{
						continue;
					}
					#endregion

					#region	特殊字段
					foreach (string arrE in specialFieldArr)
					{
						if (arrE.Contains(fName))
						{
							//获得对应规则
							StoInt = arrE.Split(']')[1];
						}
					}
					//特殊字段
					StatusSearch(ref sqlWhere, fName, fieldValueArr[index], StoInt);
					#endregion

				}
				else if ("Int64,Decimal,Double,Int32,Byte".Contains(searchType))
				{
					#region 数值

					//数值
					//---------------------谢俊---2013.8.24 12:36---------------------
					// 功能描述：数值区间的分隔符改用'|'.
					fieldValueArr[index] = fieldValueArr[index].Replace("-", "|");
					//--------------------------------------------------------------------
					//数值
					CommonTable.IntSearch(ref sqlWhere, fName, fieldValueArr[index]);
					#endregion
				}
				else if ("DateTime".Equals(searchType))
				{
					#region 日期

					//日期
					if (fieldValueArr[index].Contains(".") && !fieldValueArr[index].Contains("-"))
					{
						fieldValueArr[index] = fieldValueArr[index].Replace(".", "-");
					}
					//---------------------谢俊---2013.8.24 13:41---------------------
					// 功能描述：日期区间改用'|'分割.
					if (fieldValueArr[index].Contains("-") && !fieldValueArr[index].Contains("/"))
					{
						string[] valueArr = fieldValueArr[index].Split('-');
						for (int i = 1; i < valueArr.Length; i++)
						{
							if (valueArr[i].Length == 4)
							{
								valueArr[i] = "|" + valueArr[i];
								fieldValueArr[index] = string.Join("/", valueArr);
								fieldValueArr[index] = fieldValueArr[index].Remove(fieldValueArr[index].IndexOf("|") - 1, 1);
								break;
							}
						}
					}
					else if (fieldValueArr[index].Contains("/") && fieldValueArr[index].Contains("-"))
					{
						string[] tempArr = fieldValueArr[index].Split('-');
						if (tempArr[1].Split('/')[0].Length == 4)
						{
							fieldValueArr[index] = fieldValueArr[index].Replace("-", "|");
						}
					}

					//--------------------------------------------------------------------
					//时间				
					CommonTable.IntSearch(ref sqlWhere, fName, fieldValueArr[index], "String");
					#endregion
				}
				else if ("String".Equals(searchType))
				{
					#region 字符
					//字符
					CommonTable.OnlySearch(ref sqlWhere, fName, fieldValueArr[index], "like");
					#endregion
				}
				//索引自增
				index++;
			}
			sqlWhere = CommonTable.SqlWhereCorrection(sqlWhere, fieldName);
		}



		#region one day,tell me why?

		/// <summary>
		/// sql条件语句,and与or的组合查询.
		/// </summary>
		/// <param name="sqlWhere">条件语句</param>
		/// <param name="fieldName">条件语句中使用过的字段名(用逗号分隔)</param>
		/// <returns>返回and与or的组合查询.</returns>
		public static string SqlWhereCorrection(string sqlWhere, string fieldName)
		{
			//CommonTable.DebugInfo(sqlWhere);

			#region defence
			if (string.IsNullOrEmpty(fieldName))
			{
				return sqlWhere;
			}
			if (!sqlWhere.Contains("or"))
			{
				return sqlWhere;
			}
			#endregion

			#region variable
			//分解条件语句
			string[] andArr = sqlWhere.Split(new string[] { "and" }, StringSplitOptions.None);
			//字段名
			string[] fieldNameArr = fieldName.Split('|');
			//使用or条件的字段名
			string orFieldName = "";
			//and条件子句
			string aSql = "";
			//or条件子句
			string oSql = "";
			//临时or条件子句
			string tempOsql = "";
			//是否需要使用or子句的标识
			bool useOr = false;
			//当前使用or的字段名
			string currOrFieldName = "";
			//or子句
			string[] orWhere;
			#endregion

			#region 得到使用or的字段名
			//字段名所对应的值可能为空的.
			foreach (string fStr in fieldNameArr)
			{
				#region defence
				if (string.IsNullOrEmpty(fStr))
				{
					continue;
				}
				if (orFieldName.Contains(fStr))
				{
					continue;
				}
				#endregion

				if (fStr.Length != fieldName.Length - fieldName.Replace(fStr, "").Length)
				{
					//多个字段
					orFieldName += fStr + ",";
				}
			}
			#endregion

			//需要使用or条件子句的字段名
			string[] orFieldNameArr = orFieldName.Split(',');
			//遍历条件元素
			for (int pi = 0; pi < andArr.Length; pi++)
			{
				#region defence
				if (string.IsNullOrEmpty(andArr[pi]))
				{
					continue;
				}
				#endregion

				#region 遍历当前条件元素是否需要使用or条件
				for (int ci = 0; ci < orFieldNameArr.Length; ci++)
				{
					#region defence
					if (string.IsNullOrEmpty(orFieldNameArr[ci]))
					{
						continue;
					}
					#endregion
					if (andArr[pi].Contains(orFieldNameArr[ci]))
					{
						currOrFieldName = orFieldNameArr[ci];
						useOr = true;
						break;
					}
				}
				#endregion

				if (useOr)
				{
					#region 组建or条件子句
					//开始组建or条件子句
					tempOsql = " and (" + andArr[pi];
					//使用or条件
					#region 遍历组合or条件
					//在当前条件元素的基础上往下遍历
					for (int ci1 = pi + 1; ci1 < andArr.Length; ci1++)
					{
						#region defence


						if (string.IsNullOrEmpty(andArr[ci1]))
						{
							continue;
						}
						#endregion

						#region between
						if (andArr[pi].ToLower().Contains("between"))
						{
							//不包含or
							if (!andArr[ci1].ToLower().Contains("or"))
							{
								bool between = true;
								//遍历字段名,排除不属于同一字段的条件元素.
								for (int ci2 = 0; ci2 < fieldNameArr.Length; ci2++)
								{
									#region defence


									if (string.IsNullOrEmpty(fieldNameArr[ci2]))
									{
										continue;
									}
									#endregion
									if (andArr[ci1].Contains(fieldNameArr[ci2]))
									{
										between = false;
									}

								}

								if (between)
								{
									tempOsql = tempOsql + " and " + andArr[ci1];
									andArr[ci1] = "";
								}
							}
							else
							{
								//包含or,跳转标签.
								goto orWhere;
							}
						}
						#endregion

						#region defence
						//排除不属于同一字段的条件元素
						if (!andArr[ci1].Contains(currOrFieldName))
						{
							continue;
						}
						if (string.IsNullOrEmpty(andArr[ci1]))
						{
							continue;
						}
						#endregion

						#region 条件元素包含or

					orWhere:
						//判断下一个元素是否包含or
						if (andArr[ci1].Contains("or"))
						{

							#region 遍历or条件子句
							orWhere = andArr[ci1].Split(new string[] { "or" }, StringSplitOptions.None);
							//遍历or条件子句
							for (int ci2 = 0; ci2 < orWhere.Length; ci2++)
							{
								#region defence
								if (string.IsNullOrEmpty(orWhere[ci2]))
								{
									continue;
								}
								#endregion

								if (orWhere[ci2].Contains(currOrFieldName))
								{
									tempOsql = tempOsql + " or " + orWhere[ci2];
									orWhere[ci2] = "";
								}
								else
								{
									if (andArr[pi].ToLower().Contains("between"))
									{
										bool between = true;
										for (int ci4 = 0; ci4 < fieldNameArr.Length; ci4++)
										{
											if (string.IsNullOrEmpty(fieldNameArr[ci4]))
											{
												continue;
											}
											if (orWhere[ci2].Contains(fieldNameArr[ci4]))
											{
												between = false;
											}
										}
										if (between)
										{
											tempOsql = tempOsql + " and " + orWhere[ci2];
											orWhere[ci2] = "";
										}
									}

								}
							}
							#endregion

							#region 为条件元素重新赋值
							andArr[ci1] = "";
							for (int ci3 = 0; ci3 < orWhere.Length; ci3++)
							{
								#region defence
								if (string.IsNullOrEmpty(orWhere[ci3]))
								{
									continue;
								}
								#endregion
								if (string.IsNullOrEmpty(andArr[ci1]))
								{
									andArr[ci1] = orWhere[ci3];
								}
								else
								{
									andArr[ci1] = andArr[ci1] + " or " + orWhere[ci3];
								}

							}
							#endregion

						}
						else
						{
							//组建or条件子句
							tempOsql = tempOsql + " or " + andArr[ci1];
							andArr[ci1] = "";
						}
						#endregion

					}
					#endregion
					//闭合or条件子句
					tempOsql = tempOsql + " ) ";
					oSql = oSql + tempOsql;
					tempOsql = "";
					useOr = false;
					#endregion
				}
				else
				{

					#region 组建and条件子句
					if (string.IsNullOrEmpty(aSql))
					{
						//第一次
						aSql = andArr[pi];
					}
					else
					{
						//使用and条件
						aSql = aSql + " and " + andArr[pi];
					}
					andArr[pi] = "";
					#endregion

				}
			}
			//有or的条件语句
			if (!string.IsNullOrEmpty(oSql))
			{
				aSql = "( " + aSql + " )";
			}
			return aSql + oSql;
		}

		#endregion

	}

	public static class SetFormToModel<T>
	{





	



		//遍历实体类字段名
		public static string ergodicAttributes(T t)
		{
			StringBuilder fieldName = new StringBuilder();
			Type type = t.GetType();
			PropertyInfo[] pi = type.GetProperties();
			foreach (PropertyInfo p in pi)
			{
				fieldName.Append(p.Name + ",");
			}
			CommonTable.RemoveLastChar(ref fieldName, ',');
			return fieldName.ToString();
		}

		/// <summary> 
		/// 将表单赋予对象 
		/// </summary> 
		/// <param name="t">实体对象</param> 
		/// <param name="form">表单集合</param> 
		public static void GetValue(T t, NameValueCollection form)
		{
			//返回当前 System.Type 的所有公共属性。
			PropertyInfo[] pi = t.GetType().GetProperties();
			foreach (PropertyInfo p in pi)
			{
				//p.Name即实体类中的字段名
				//判断是否存在与当前字段相对应的值.
				if (!string.IsNullOrEmpty(form[p.Name]))
				{
					p.SetValue(t, Convert.ChangeType(form[p.Name], p.PropertyType), null);

				}
				//---------------------谢俊---2013.9.20 21:4---------------------
				// 功能描述：字符类型没有赋值为null,与存储过程动态定义sql语句存在冲突.
				if (p.PropertyType.Name == "String" && p.GetValue(t, null) == null)
				{
					p.SetValue(t, Convert.ChangeType("", p.PropertyType), null);
				}
				//--------------------------------------------------------------------


				//---------------------谢俊---2013.9.24 11:6---------------------
				// 功能描述：日期默认值
				//if (p.PropertyType.Name == "DateTime" && DateTime.Parse(p.GetValue(t, null).ToString()) == DateTime.Parse("0001/1/1 星期一 0:00:00"))
				//{
				//    p.SetValue(t,Convert.ChangeType("1/1/1753 12:00:00",p.PropertyType),null);
				//        //DateTime.Parse("1/1/1753 12:00:00 ")
				//}
				//--------------------------------------------------------------------
				//--------------------------------------------------------------------

				//try
				//{
				//赋值
				//取值
				//if (p.Name == "fo_binumber")
				//{
				//    object o = type.GetProperty("fo_binumber").GetValue(t, null);
				//    string Value = Convert.ToString(o);
				//}		
				//            }
				//catch (Exception e)
				//{
				//    return "类型转换失败!     字段名:" + p.Name + "   " + "表单值:" + form[p.Name] + "    " + "错误信息:" + e.Message;

				//}	

			}

			//return "Success";
		}

		/// <summary>
		/// 取得分类的字段名集合
		/// </summary>
		/// <param name="t"></param>
		/// <returns>分类的字段名集合,用'|'分割.Int|Status|String|Date</returns>
		public static string GetFieldNameCollection(T t)
		{
			//数值类型字段名集合
			StringBuilder IntFieldName = new StringBuilder();
			//非数值类型字段名集合
			StringBuilder SFieldName = new StringBuilder();
			//状态字段名
			string statusFieldName = string.Empty;
			//日期字段名
			string DateFieldName = string.Empty;
			//获取当前实例的 System.Type。
			Type type = t.GetType();
			//返回当前 System.Type 的所有公共属性。
			PropertyInfo[] pi = type.GetProperties();
			//数值类型
			string IntTypeName = "Int64,Decimal,Double,Int32";
			foreach (PropertyInfo p in pi)
			{
				//|| p.Name.ToLower().Contains("type")
				//取得表的状态字段名
				if (p.Name.ToLower().Contains("status"))
				{
					statusFieldName = p.Name + ",";
					continue;
				}
				//取得表的日期字段名
				if (p.PropertyType.Name == "DateTime")
				//if (p.PropertyType.Name == "DateTime" || p.Name.ToLower().Contains("date") || p.Name.ToLower().Contains("time"))
				{
					DateFieldName += p.Name + ",";
					continue;
				}
				if (IntTypeName.Contains(p.GetGetMethod().ReturnType.Name))
				{
					//数值类型
					IntFieldName.Append(p.Name + ",");
					continue;
				}
				//字符类型
				SFieldName.Append(p.Name + ",");
			}
			//分类的字段名集合
			return IntFieldName.ToString() + "|" + statusFieldName + "|" + SFieldName.ToString() + "|" + DateFieldName;
		}

		/// <summary>
		/// 自动生成实体类字段名
		/// /*
		/// string FN = SetFormToModel<Model.FM_fundorder>.ModelFieldName(model, 
		/// "TableName,PrimaryKey","fo_status,fo_status", "0,1,3,4|0,1,3,4", 
		/// "禁用,可用,审核,复核|禁用,可用,审核,复核");
		/// */
		/// </summary>
		/// <param name="t">实体类</param>
		/// <param name="remove">要排除的字段名</param>
		/// <param name="caseFieldName">要加case表达式的字段名,多字段时使用','分割.</param>
		/// <param name="whenValue">when的字符集,多字段时使用'|'分割.</param>
		/// <param name="thenValue">then的字符集,多字段时使用'|'分割.</param>
		/// <returns>返回实体类的字段名</returns>
		public static string ModelFieldName(T t, string remove = "", string caseFieldName = "", string whenValue = "", string thenValue = "")
		{

			Type type = t.GetType();
			PropertyInfo[] pi = type.GetProperties();
			StringBuilder fieldName = new StringBuilder();
			foreach (PropertyInfo p in pi)
			{
				fieldName.Append(p.Name + ",");
			}
			if (!string.IsNullOrEmpty(remove))
			{
				string[] removeArr = remove.Split(',');
				foreach (string i in removeArr)
				{
					fieldName.Replace(i + ",", "");
				}
			}
			//case表达式
			if (caseFieldName != "" && whenValue != "" && thenValue != "")
			{
				string[] caseFieldNameArr = caseFieldName.Split(',');
				//去除需要case的字段名
				foreach (string i in caseFieldNameArr)
				{
					fieldName.Replace(i + ",", "");
				}
				//支持多字段
				string[] tempWhen = whenValue.Split('|');
				string[] tempThen = thenValue.Split('|');
				for (int s = 0; s < caseFieldNameArr.Length; s++)
				{
					fieldName.Append("case " + caseFieldNameArr[s]);
					for (int u = 0; u < tempWhen[s].Split(',').Length; u++)
					{
						fieldName.Append(" when " + tempWhen[s].Split(',')[u] + " then '" + tempThen[s].Split(',')[u] + "'");
					}
					fieldName.Append(" end " + caseFieldNameArr[s] + ",");
				}
			}
			if (fieldName.ToString().LastIndexOf(',') == fieldName.Length - 1)
			{
				fieldName.Remove(fieldName.Length - 1, 1);
			}
			return fieldName.ToString();
		}



		/// <summary>
		/// 实体类数据输出
		/// </summary>
		/// <param name="t">实体类</param>
		/// <returns>返回字段值</returns>
		public static string ModelValue(T t, NameValueCollection form = null)
		{
			StringBuilder fieldValue = new StringBuilder();
			PropertyInfo[] pi = t.GetType().GetProperties();
			string requestValue = "";
			foreach (PropertyInfo p in pi)
			{
				if (form != null)
				{
					requestValue = form[p.Name];
				}
				fieldValue.Append(p.Name + " : " + p.GetValue(t, null) + "	requestValue=" + requestValue + "\n");
			}
			return fieldValue.ToString();
		}
		///// <summary> 
		///// 将对象赋予表单 
		///// </summary> 
		///// <param name="t">实体对象</param> 
		///// <param name="c">页面对象</param> 
		//public static void SetValue(T t, Page page)
		//{
		//    Type type = t.GetType();
		//    PropertyInfo[] pi = type.GetProperties();
		//    foreach (PropertyInfo p in pi)
		//    {
		//        System.Web.UI.HtmlControls.HtmlInputText text = page.FindControl(p.Name) as System.Web.UI.HtmlControls.HtmlInputText;

		//        if (text != null)
		//        {
		//            text.Value = p.GetValue(t, null).ToString();
		//        }
		//    }

		//}

	}

	/// <summary>
	/// DataTable与实体类互相转换
	/// </summary>
	/// <typeparam name="T">实体类</typeparam>
	public class ModelHandler<T> where T : new()
	{
		#region DataTable转换成实体类

		/// <summary>
		/// 填充对象列表：用DataSet的第一个表填充实体类
		/// </summary>
		/// <param name="ds">DataSet</param>
		/// <returns></returns>
		public List<T> FillModel(DataSet ds)
		{
			if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0)
			{
				return null;
			}
			else
			{
				return FillModel(ds.Tables[0]);
			}
		}

		/// <summary>  
		/// 填充对象列表：用DataSet的第index个表填充实体类
		/// </summary>  
		public List<T> FillModel(DataSet ds, int index)
		{
			if (ds == null || ds.Tables.Count <= index || ds.Tables[index].Rows.Count == 0)
			{
				return null;
			}
			else
			{
				return FillModel(ds.Tables[index]);
			}
		}

		/// <summary>  
		/// 填充对象列表：用DataTable填充实体类
		/// </summary>  
		public List<T> FillModel(DataTable dt)
		{
			if (dt == null || dt.Rows.Count == 0)
			{
				return null;
			}
			List<T> modelList = new List<T>();
			foreach (DataRow dr in dt.Rows)
			{
				//T model = (T)Activator.CreateInstance(typeof(T));  
				T model = new T();
				foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
				{
					model.GetType().GetProperty(propertyInfo.Name).SetValue(model, dr[propertyInfo.Name], null);
				}
				modelList.Add(model);
			}
			return modelList;
		}

		/// <summary>  
		/// 填充对象：用DataRow填充实体类
		/// </summary>  
		public T FillModel(DataRow dr)
		{
			if (dr == null)
			{
				return default(T);
			}

			//T model = (T)Activator.CreateInstance(typeof(T));  
			T model = new T();
			foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
			{
				model.GetType().GetProperty(propertyInfo.Name).SetValue(model, dr[propertyInfo.Name], null);
			}
			return model;
		}

		#endregion

		#region 实体类转换成DataTable

		/// <summary>
		/// 实体类转换成DataSet
		/// </summary>
		/// <param name="modelList">实体类列表</param>
		/// <returns></returns>
		public DataSet FillDataSet(List<T> modelList)
		{
			if (modelList == null || modelList.Count == 0)
			{
				return null;
			}
			else
			{
				DataSet ds = new DataSet();
				ds.Tables.Add(FillDataTable(modelList));
				return ds;
			}
		}

		/// <summary>
		/// 实体类转换成DataTable
		/// </summary>
		/// <param name="modelList">实体类列表</param>
		/// <returns></returns>
		public DataTable FillDataTable(List<T> modelList)
		{
			if (modelList == null || modelList.Count == 0)
			{
				return null;
			}
			DataTable dt = CreateData(modelList[0]);

			foreach (T model in modelList)
			{
				DataRow dataRow = dt.NewRow();
				foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
				{
					dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
				}
				dt.Rows.Add(dataRow);
			}
			return dt;
		}

		/// <summary>
		/// 根据实体类得到表结构
		/// </summary>
		/// <param name="model">实体类</param>
		/// <returns></returns>
		private DataTable CreateData(T model)
		{
			DataTable dataTable = new DataTable(typeof(T).Name);
			foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
			{
				dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
			}
			return dataTable;
		}

		#endregion
	}

	public class CommonCRUD
	{
		public static bool Delete(string tbl, string idfield, int id)
		{
			StringBuilder builder = new StringBuilder();
			builder.AppendFormat("delete from {0} ", tbl);
			builder.AppendFormat(" where {0}=@id ", idfield);
			SqlParameter[] cmdParms = new SqlParameter[] { new SqlParameter("@id", SqlDbType.Int) };
			cmdParms[0].Value = id;
			return (DbHelperSQL.ExecuteSql(builder.ToString(), cmdParms) > 0);
		}

		public static int GetRecordCount(string tbl, string strWhere)
		{
			StringBuilder builder = new StringBuilder();
			builder.AppendFormat("select count(1) FROM {0} ", tbl);
			if (strWhere.Trim() != "")
			{
				builder.Append(" where " + strWhere);
			}
			object single = DbHelperSQL.GetSingle(builder.ToString());
			if (single == null)
			{
				return 0;
			}
			return Convert.ToInt32(single);
		}


		/// <summary>
		/// 获得数据列表
		/// </summary>
		public DataSet GetList(string tb, string strWhere)
		{
			StringBuilder strSql = new StringBuilder();
			strSql.Append("select * from " + tb);
			if (strWhere.Trim() != "")
			{
				strSql.Append(" where " + strWhere);
			}
			return DbHelperSQL.Query(strSql.ToString());
		}


		#region 分页的json数据
		

		//public static string GetDataGridJson(DataTable JsonTable, DataTable CountTable)
		//{
		//    return "{ \"total\":" + CountTable.Rows[0][0].ToString() + ",\"rows\":" + TableToBasicJson(JsonTable) + "}";
		//}

		//public static string GetDataGridJson(DataTable JsonTable, int Count)
		//{
		//    return "{ \"total\":" + Count + ",\"rows\":" + TableToBasicJson(JsonTable) + "}";
		//}

		//public static string GetDataGridJson(DataTable JsonTable, DataTable CountTable, DataTable FooterTable)
		//{
		//    return "{ \"total\":" + CountTable.Rows[0][0].ToString() + ",\"rows\":" + TableToBasicJson(JsonTable) + ",\"footer\":" + TableToBasicJson(FooterTable) + "}";
		//}

		//public static string GetDataGridJson(DataTable JsonTable, int Count, DataTable FooterTable)
		//{
		//    return "{ \"total\":" + Count + ",\"rows\":" + TableToBasicJson(JsonTable) + ",\"footer\":" + TableToBasicJson(FooterTable) + "}";
		//}

		//public string Combotree(DataTable JsonTable, string idField, string textField)
		//{
		//    JsonTable.Columns[idField].ColumnName = "id";
		//    JsonTable.Columns[textField].ColumnName = "text";
		//    DataColumn dcState = new DataColumn("state", Type.GetType("System.String"));
		//    dcState.DefaultValue = "closed";
		//    JsonTable.Columns.Add(dcState);
		//    return TableToBasicJson(JsonTable);
		//}

		//public string TableToJsonAsync(DataTable JsonTable)
		//{
		//    DataColumn dcState = new DataColumn("state", Type.GetType("System.String"));
		//    dcState.DefaultValue = "closed";
		//    JsonTable.Columns.Add(dcState);
		//    return TableToBasicJson(JsonTable);
		//}
		///// <summary>
		///// 根据SQL语句返Json格式字符串
		///// </summary>
		///// <param name="SqlString">查询语句</param>
		//public string GetListJson(DataTable JsonTable)
		//{
		//    return TableToBasicJson(JsonTable);
		//}

		///// <summary>
		///// 根据表得到Json格式字符串
		///// </summary>
		///// <param name="JsonTable">数据表</param>
		///// <returns>Json格式字符串</returns>
		//public static string TableToBasicJson(DataTable JsonTable)
		//{
		//    JavaScriptSerializer Jss = new JavaScriptSerializer();
		//    //组合Json数据
		//    List<Dictionary<string, object>> JsonList = new List<Dictionary<string, object>>();
		//    foreach (DataRow Row in JsonTable.Rows)
		//    {
		//        Dictionary<string, object> JsonDrow = new Dictionary<string, object>();

		//        foreach (DataColumn Col in JsonTable.Columns)
		//        {
		//            if (Col.DataType == System.Type.GetType("System.DateTime"))
		//            {
		//                string DtStr = "";

		//                if (string.IsNullOrEmpty(Row[Col.ColumnName].ToString()))
		//                {
		//                    DtStr = "";
		//                }
		//                else
		//                {
		//                    DateTime Dt = Convert.ToDateTime(Row[Col.ColumnName].ToString());

		//                    DtStr = Dt.ToString("yyyy-MM-dd HH:mm");
		//                }

		//                JsonDrow.Add(Col.ColumnName.ToLower(), DtStr);
		//            }
		//            else
		//            {
		//                JsonDrow.Add(Col.ColumnName.ToLower(), Row[Col.ColumnName].ToString());
		//            }
		//        }

		//        JsonList.Add(JsonDrow);
		//    }

		//    return Jss.Serialize(JsonList);
		//}

		///// <summary> 
		///// Json转DataTable 
		///// </summary> 
		///// <param name="json">Json格式字符串</param> 
		///// <returns>数据表</returns> 
		//public DataTable JsonToTable(string JsonString)
		//{
		//    List<Dictionary<string, object>> JsonList = new List<Dictionary<string, object>>();

		//    JsonList = Jss.Deserialize<List<Dictionary<string, object>>>(JsonString);

		//    DataTable JsonTable = new DataTable();

		//    if (JsonList.Count > 0)
		//    {
		//        foreach (Dictionary<string, object> JsonDrow in JsonList)
		//        {
		//            if (JsonTable.Columns.Count == 0)
		//            {
		//                foreach (string Key in JsonDrow.Keys)
		//                {
		//                    JsonTable.Columns.Add(Key, JsonDrow[Key].GetType());
		//                }
		//            }

		//            DataRow JsonRow = JsonTable.NewRow();

		//            foreach (string Key in JsonDrow.Keys)
		//            {
		//                JsonRow[Key] = JsonDrow[Key];
		//            }

		//            JsonTable.Rows.Add(JsonRow);
		//        }
		//    }

		//    return JsonTable;
		//}

		#endregion

	}



}
